﻿using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Plugin;
using Neo4JConnector.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Neo4JConnector
{
    [Icon("pack://application:,,,/Neo4JConnector;component/Resources/Icon.png")]
    [Category("neo4j图数据库")]
    [OrderWeight(210)]
    internal class DeleteRelation : BaseNeo4JOp
    {
        [SearchableProperty]
        [FormulaProperty]
        [DisplayName("节点1的标签")]
        [Description("类似于数据库中的表，用于对节点进行分类。")]
        [OrderWeight(100)]
        public object Label1Expr { get; set; }

        [SearchableProperty]
        [FormulaProperty]
        [DisplayName("节点1的ID")]
        [Description("类似于数据库中的行ID，在同一个表内需要保持唯一。")]
        [OrderWeight(101)]
        public object ID1Expr { get; set; }

        [SearchableProperty]
        [FormulaProperty]
        [DisplayName("节点2的标签")]
        [Description("类似于数据库中的表，用于对节点进行分类。")]
        [OrderWeight(110)]
        public object Label2Expr { get; set; }

        [SearchableProperty]
        [FormulaProperty]
        [DisplayName("节点2的ID")]
        [Description("类似于数据库中的行ID，在同一个表内需要保持唯一。")]
        [OrderWeight(111)]
        public object ID2Expr { get; set; }

        [SearchableProperty]
        [FormulaProperty]
        [DisplayName("关系")]
        [Description("关系的类型名称，如：DependsOn、RelatedTo、PartOf、Requires、Custom1和Custom2。")]
        [OrderWeight(200)]
        public object RelationTypeExpr { get; set; }

        public override async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var id1 = (await dataContext.EvaluateFormulaAsync(ID1Expr))?.ToString() ?? "";
            var id2 = (await dataContext.EvaluateFormulaAsync(ID2Expr))?.ToString() ?? "";
            var label1 = (await dataContext.EvaluateFormulaAsync(Label1Expr))?.ToString() ?? "";
            var label2 = (await dataContext.EvaluateFormulaAsync(Label2Expr))?.ToString() ?? "";

            var relation = (await dataContext.EvaluateFormulaAsync(RelationTypeExpr))?.ToString() ?? "";

            if (string.IsNullOrEmpty(id1) || string.IsNullOrEmpty(id2) || string.IsNullOrEmpty(label1) || string.IsNullOrEmpty(label2) || string.IsNullOrEmpty(relation))
            {
                throw new Exception("节点的标签、ID和关系不能为空。");
            }


            if (!Validators.IsValidLabel(label1) || !Validators.IsValidLabel(label2))
                throw new Exception("节点的标签包含非法字符，仅支持字母数字和下划线，且需要以字母开头。");

            var client = await getClient(dataContext);

            await client.RemoveRelation(label1, id1, label2, id2, relation);


            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "neo4j：删除节点的关系";
        }
    }
}
